package com.hcbd.tdwt.base;

import android.text.TextUtils;
import android.util.Log;

import com.hcbd.tdwt.util.ConvertData;
import com.hcbd.tdwt.util.DateUtils;
import com.pancoit.compression.ZDCompression;
import com.pangu.bdsdk2021.util.BdCommonMethod;
import com.hcbd.tdwt.ui.xingyu.vo.Position;
import com.hcbd.tdwt.ui.xingyu.vo.PositionVo;
import com.hcbd.tdwt.ui.xingyu.vo.SendImgDataVO;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;

import java.util.Calendar;
import java.util.List;
import java.util.Objects;

public class ConvertToBdMsgTool {
    /**
     * 报警
     * 0x13
     *
     * @return
     * @throws Exception
     */
    // 13 00 032689CBB5 06C3E04E 0161519E FFFF 00 00 01
    public static String castUserMessageTo0x13(String toPhone, Position position, String situation,  String healthStatus, int num) {
        StringBuilder hex;
        byte[] requestHeaderBytes = new byte[2];
        //消息类型0x13
        requestHeaderBytes[0] = (byte) 0x13;
        //保留字段1位
        requestHeaderBytes[1] = (byte) 0x00;
        hex = new StringBuilder(ConvertData.bytes2hex(requestHeaderBytes));
        //联系人
        String phoneHex = ConvertData.longToHex(Long.parseLong(toPhone)).substring(6);
        hex.append(phoneHex);
        //位置
        if (position != null) {
            String positionHex = ConvertData.positionToHex2(position);
            hex.append(positionHex);
        }
        //状态
        hex.append(situation);
        //身体状况
        hex.append(healthStatus);
        //人数
        hex.append(ConvertData.intToHex(num).substring(6));

        return hex.toString().toUpperCase();
    }
    /**
     * 报平安
     * 0x14
     *
     * @param phone    接收者号码
     * @param safeContent 平安内容
     * @param position 位置信息
     * @return
     */
    public static String castUserMessageTo0x14(String phone,String safeContent, Position position) {
        StringBuilder hex;
        byte[] requestHeaderBytes = new byte[3];
        //消息类型0x14
        requestHeaderBytes[0] = (byte) 0x14;
        //保留字段2位
        requestHeaderBytes[1] = (byte) 0x00;
        requestHeaderBytes[2] = (byte) 0x00;
        hex = new StringBuilder(ConvertData.bytes2hex(requestHeaderBytes));
        //联系人
        String phoneHex = ConvertData.longToHex(Long.parseLong(phone)).substring(6);
        hex.append(phoneHex);
        //位置
        if (position != null) {
            String positionHex = ConvertData.positionToHex2(position);
            hex.append(positionHex);
        }
        String contentHex = ConvertData.stringToHex(safeContent);
        hex.append(contentHex);
        return hex.toString().toUpperCase();
    }
    /**
     * 北斗网到北斗网(不带位置)
     * 0x90
     *
     * @param userMessage
     * @return
     */
    public  static String castUserMessageTo0x90(UserMessageVO userMessage) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0x90
        byte requestHeaderByte = (byte) 0x90;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //保留字段5位
        for (int i = 0; i < 5; i++) {
            hex.append(ConvertData.byte2hex((byte) 0x00));
        }

        //时间戳
        hex.append(ConvertData.longToHex(Long.parseLong(Objects.requireNonNull(DateUtils.dateToTimeStamp(userMessage.getSendTime(), "")))).substring(8));
        //内容
        String contentHex = ConvertData.stringToHex(userMessage.getContent());
        hex.append(contentHex);

        return hex.toString().toUpperCase();
    }
    /**
     * 北斗网到北斗网(带位置)
     * 0x91
     *
     * @param userMessage
     * @return
     */
    public static String castUserMessageTo0x91(UserMessageVO userMessage) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0x91
        byte requestHeaderByte = (byte) 0x91;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //保留字段5位
        for (int i = 0; i < 5; i++) {
            hex.append(ConvertData.byte2hex((byte) 0x00));
        }

        //时间戳
        hex.append(ConvertData.longToHex(Long.parseLong(DateUtils.dateToTimeStamp(userMessage.getSendTime(), ""))).substring(8));
        //位置
        if (userMessage.getLongitude() != null || userMessage.getLatitude() != null) {
            String positionHex = ConvertData.positionToHex(Double.parseDouble(userMessage.getLongitude()), Double.parseDouble(userMessage.getLatitude()), Double.parseDouble(userMessage.getAltitude()));
            hex.append(positionHex);
        }
        //内容
        String contentHex = ConvertData.stringToHex(userMessage.getContent());
        hex.append(contentHex);

        return hex.toString().toUpperCase();
    }

    /**
     * 北斗网到公网(带位置)
     * 0x93
     *
     * @param userMessageVO
     * @return
     */
    public static String  castUserMessageTo0x93(UserMessageVO userMessageVO,String towHo) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0x93
        byte requestHeaderByte = (byte) 0x93;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码
        if (towHo != null) {
            byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(towHo, 10));
            hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));
        }
        //时间戳
        hex.append(ConvertData.longToHex(Long.parseLong(DateUtils.dateToTimeStamp(userMessageVO.getSendTime(), ""))).substring(8));
        //位置

        if (!TextUtils.isEmpty(userMessageVO.getLongitude())&&!TextUtils.isEmpty(userMessageVO.getLatitude())&&!TextUtils.isEmpty(userMessageVO.getAltitude())) {
            String positionHex = ConvertData.positionToHex(Double.parseDouble(userMessageVO.getLongitude()), Double.parseDouble(userMessageVO.getLatitude()), Double.parseDouble(userMessageVO.getAltitude()));
            hex.append(positionHex);
        }
        //内容
        String contentHex = ConvertData.stringToHex(userMessageVO.getContent());
        hex.append(contentHex);
        return hex.toString().toUpperCase();
    }

    /**
     * 北斗网到短信(带位置)
     * 0x95
     *
     * @param userMessage
     * @return
     */
    public static String castUserMessageTo0x95(UserMessageVO userMessage,String toWho) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0x95
        byte requestHeaderByte = (byte) 0x95;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码
        if (toWho != null) {
            byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(toWho, 10));
            hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));
        }
        //时间戳
        hex.append(ConvertData.longToHex(Long.parseLong(DateUtils.dateToTimeStamp(userMessage.getSendTime(), ""))).substring(8));
        //位置
        if (userMessage.getLongitude() != null || userMessage.getLatitude() != null) {
            String positionHex = ConvertData.positionToHex(Double.parseDouble(userMessage.getLongitude()), Double.parseDouble(userMessage.getLatitude()), Double.parseDouble(userMessage.getAltitude()));
            hex.append(positionHex);
        }
        //内容
        String contentHex = ConvertData.stringToHex(userMessage.getContent());
        hex.append(contentHex);
        return hex.toString().toUpperCase();
    }

    /**
     * 位置上报
     * 0x15
     *
     * @param positions 位置列表
     * @param serial    轨迹编号
     * @return
     * @throws Exception
     */
    public  static String castUserMessageTo0x15(List<PositionVo> positions, int serial) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0x15,保留字段5位
        byte[] requestHeaderBytes = new byte[6];
        requestHeaderBytes[0] = (byte) 0x15;
        for (int i = 1; i < 6; i++) {
            requestHeaderBytes[i] = (byte) 0x00;
        }
        hex = new StringBuilder(ConvertData.bytes2hex(requestHeaderBytes));
        //轨迹编号
        hex.append(ConvertData.intToHex(serial).substring(6));
        //位置个数,num∈[0,5]
        hex.append(ConvertData.intToHex(positions.size()).substring(6));
        //位置
        for (int i = 0; i < positions.size(); i++) {
            PositionVo position = positions.get(i);
            hex.append(ConvertData.positionToHex(position));
            //时间戳
            String timeHex = ConvertData.longToHex(position.getTime()).substring(8);
            hex.append(timeHex);
        }
        return hex.toString().toUpperCase();
    }
    /**
     * N5位置上报
     *
     * @param positions 位置列表
     * @param freq    采样频度
     * @return
     * @throws Exception
     */
    // 00 A4 18030C0D2F21 001E 04 45 711D3A63 4E 17091519 0039 007A0145711D3B3B4E1709145A000E00700145711E005D4E17091240001001320145711E01004E1709122E0009001A0100
    public  static String castUserMessageTo0x04N5(List<PositionVo> positions, int freq) {
        //16进制北斗内容
        byte[] requestHeaderBytes = new byte[2];
        requestHeaderBytes[0] = (byte) 0x00;
        requestHeaderBytes[1] = (byte) 0xA4;
        StringBuilder hex = new StringBuilder(ConvertData.bytes2hex(requestHeaderBytes));
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        year=year-2000;
        hex.append(ConvertData.intToHex(year).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.MONTH)+1).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.DAY_OF_MONTH)).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.HOUR_OF_DAY)).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.MINUTE)).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.SECOND)).substring(6));
        int size=positions.size();
        freq=freq/size;
        Log.e("freq",String.valueOf(freq));
        String freqStr=ConvertData.intToHex(freq).substring(4);
        //采样频度
        hex.append(freqStr);
        //位置个数,num∈[0,5]
        hex.append(ConvertData.intToHex(size).substring(6));
        //位置
        for (int i = 0; i < size; i++) {
            PositionVo position = positions.get(i);
            hex.append(ConvertData.positionVoToHex(position));
        }
        String checkCode = BdCommonMethod.getCheckCode_0007(BdCommonMethod.castHanziStringToHexString(hex.toString()));
        hex.append(checkCode);
        return hex.toString().toUpperCase();
    }
    /**
     * N5SoS上报
     *
     * @return
     * @throws Exception
     */
    public  static String castUserMessageTo0xEEN5() {
        //16进制北斗内容
        byte[] requestHeaderBytes = new byte[2];
        requestHeaderBytes[0] = (byte) 0x01;
        requestHeaderBytes[1] = (byte) 0xEE;
        StringBuilder hex = new StringBuilder(ConvertData.bytes2hex(requestHeaderBytes));
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        year=year-2000;
        hex.append(ConvertData.intToHex(year).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.MONTH)+1).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.DAY_OF_MONTH)).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.HOUR_OF_DAY)).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.MINUTE)).substring(6));
        hex.append(ConvertData.intToHex(c.get(Calendar.SECOND)).substring(6));
        String logHex=ConvertData.posDFMCoverHex(BeidouBoxParams.gpsLonDou);
        String latHex=ConvertData.posDFMCoverHex(BeidouBoxParams.gpsLatDou);
        String speedHex=ConvertData.intToHex((int)BeidouBoxParams.speed).substring(4);
        String bearingHex=ConvertData.intToHex((int)BeidouBoxParams.bearing).substring(4);
        String altitudeHex=ConvertData.intToHex((int)BeidouBoxParams.gpsAltitude).substring(4);
        hex.append("45");
        hex.append(logHex);
        hex.append("4E");
        hex.append(latHex);
        hex.append(speedHex);
        hex.append(bearingHex);
        hex.append(altitudeHex);
        hex.append("64");
        String checkCode = BdCommonMethod.getCheckCode_0007(BdCommonMethod.castHanziStringToHexString(hex.toString()));
        hex.append(checkCode);
        return hex.toString().toUpperCase();
    }



    /***
     * 发送语音
     * @param userMessage
     * @return
     */
    public static String castUserMessageTo0xA8(UserMessageVO userMessage,String toWho,int seconds) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0xA8
        byte requestHeaderByte = (byte) 0xA8;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码
        if (toWho!= null) {
            byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(toWho, 10));
            hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));
        }else {
            //保留字段5位
            for (int i = 0; i < 5; i++) {
                hex.append(ConvertData.byte2hex((byte) 0x00));
            }
        }
        //时间戳
        hex.append(ConvertData.longToHex(Long.parseLong(DateUtils.dateToTimeStamp(userMessage.getSendTime(), ""))).substring(8));

        //音频长度
        hex.append(ConvertData.intToHex(seconds).substring(6));
        try {
            byte[] zipBytes;
            if(AuthManger.getAuthManger().isVoiceOnline()){
                zipBytes= ZDCompression.getInstance().zip(userMessage.getContent(),getEncoderCodeRate(userMessage.getSeconds()));
            }else{
                zipBytes= ZDCompression.getInstance().off_voice_zip(userMessage.getContent(),getEncoderCodeRate(userMessage.getSeconds()));
            }
            Log.e("------","压缩后大小:"+zipBytes.length);
            // 语音压缩后的内容
            hex.append(ConvertData.bytes2hex(zipBytes));
        } catch (Exception e){
            e.printStackTrace();
        }
        return hex.toString().toUpperCase();
    }
    /***
     * 发送语音
     * @param userMessage
     * @return
     */
    public static String castUserMessageTo0xA7(UserMessageVO userMessage,String toWho) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0xA8
        byte requestHeaderByte = (byte) 0xA7;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码
        if (toWho!= null) {
            byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(toWho, 10));
            hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));
        }else {
            //保留字段5位
            for (int i = 0; i < 5; i++) {
                hex.append(ConvertData.byte2hex((byte) 0x00));
            }
        }
        try {
            byte[] zipBytes;
            if(AuthManger.getAuthManger().isVoiceOnline()){
                zipBytes= ZDCompression.getInstance().zip(userMessage.getContent(),Constant.encoderCodeRate);
            }else{
                zipBytes= ZDCompression.getInstance().off_voice_zip(userMessage.getContent(),Constant.encoderCodeRate);
            }
            Log.e("------","压缩后大小:"+zipBytes.length);
            // 语音压缩后的内容
            hex.append(ConvertData.bytes2hex(zipBytes));
        } catch (Exception e){
            e.printStackTrace();
        }
        return hex.toString().toUpperCase();
    }

    public static int getEncoderCodeRate(int seconds){//根据秒数及卡等级来使用不同的压缩率
        int encoderCodeRate=ZDCompression.bitRate_450;
        if(BeidouBoxParams.cardType==5) {
            if (7 > seconds) {
                encoderCodeRate = ZDCompression.bitRate_2400;
            } else if (12 > seconds) {
                encoderCodeRate = ZDCompression.bitRate_1200;
            } else if (17 > seconds) {
                encoderCodeRate = ZDCompression.bitRate_700;
            }
        }else if(BeidouBoxParams.cardType==4){
            if(6 > seconds){
                encoderCodeRate = ZDCompression.bitRate_1200;
            }else if (10 > seconds) {
                encoderCodeRate = ZDCompression.bitRate_700;
            }
        }
        Log.e("encoderCodeRate:",""+encoderCodeRate);
        return encoderCodeRate;
    }
    /**
     * A4类型消息
     *
     * @param userMessage
     * @return
     */
    public static String castUserMessageToA4(UserMessageVO userMessage,boolean isLoc) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0xA4
        byte requestHeaderByte = (byte) 0xA4;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //内容
        String content =userMessage.getContent();
        if(isLoc){
            content=content+"(POS:"+userMessage.getLongitude()+","+userMessage.getLatitude()+")";
        }
        Log.e("content:",content);
        String contentHex=ConvertData.stringToHex(content);
        //位置
        hex.append(contentHex);
        //北斗消息实体类
        return hex.toString().toUpperCase();
    }

    public static String castUserMessageTo0xA9(SendImgDataVO sendImgDataVO,String str) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0xA9 1个字节
        byte requestHeaderByte = (byte) 0xA9;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //接收者电话号码5个字节
        byte[] phoneBytes = ConvertData.long2bytes(Long.parseLong(str, 10));
        hex.append(ConvertData.bytes2hex(phoneBytes).substring(6));

        hex.append(ConvertData.longToHex(Long.parseLong(sendImgDataVO.getCreateTime())).substring(8));
        //总包数量
        hex.append(ConvertData.toLength(String.format("%x",sendImgDataVO.getPackageSize()), 2));
        //当前包序号
        hex.append(ConvertData.toLength(String.format("%x", sendImgDataVO.getId()), 2));
        try {
            String content=ConvertData.bytes2hex(sendImgDataVO.getContent());
            hex.append(content);
        } catch (Exception e){
            e.printStackTrace();
        }
        return hex.toString().toUpperCase();
    }
    /**
     * 获取天气预报
     * 0x18
     *
     * @param mode     获取类型：【0：实时天气】【1：未来3天天气】【2：灾害预警】
     * @param position 要获取天气的位置信息
     * @return
     */
    public static String castUserMessageTo0x18(int mode, Position position) {
        //16进制北斗内容
        StringBuilder hex;
        //消息类型0x18
        byte requestHeaderByte = (byte) 0x18;
        hex = new StringBuilder(ConvertData.byte2hex(requestHeaderByte));
        //获取类型：【0：实时天气】【1：未来3天天气】【2：灾害预警】
        hex.append(ConvertData.intToHex(mode).substring(6));
        //要获取天气的位置信息
        if (position != null) {
            String positionHex = ConvertData.positionToHex(position);
            hex.append(positionHex);
        }

        return hex.toString().toUpperCase();
    }
}
